﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.ContatoPack
{
    
	[Serializable()]
    public class Contato : BusinessBase<Contato>
    {
		#region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private string _telefone = string.Empty;

        private string _celular = string.Empty;

        private string _fax = string.Empty;

        private string _caixaPostal = string.Empty;

        private string _email = string.Empty;

        


        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public string Telefone
        {
            get
            {
                CanReadProperty("Telefone", true);
                return _telefone;
            }
            set
            {
                CanWriteProperty("Telefone", true);
                if (value == null) value = string.Empty;
                if (!_telefone.Equals(value))
                {
                    _telefone = value;
                    PropertyHasChanged("Telefone");
                }
            }
        }

        public string Celular
        {
            get
            {
                CanReadProperty("Celular", true);
                return _celular;
            }
            set
            {
                CanWriteProperty("Celular", true);
                if (value == null) value = string.Empty;
                if (!_celular.Equals(value))
                {
                    _celular = value;
                    PropertyHasChanged("Celular");
                }
            }
        }

        public string Fax
        {
            get
            {
                CanReadProperty("Fax", true);
                return _fax;
            }
            set
            {
                CanWriteProperty("Fax", true);
                if (value == null) value = string.Empty;
                if (!_fax.Equals(value))
                {
                    _fax = value;
                    PropertyHasChanged("Fax");
                }
            }
        }

        public string CaixaPostal
        {
            get
            {
                CanReadProperty("CaixaPostal", true);
                return _caixaPostal;
            }
            set
            {
                CanWriteProperty("CaixaPostal", true);
                if (value == null) value = string.Empty;
                if (!_caixaPostal.Equals(value))
                {
                    _caixaPostal = value;
                    PropertyHasChanged("CaixaPostal");
                }
            }
        }

        public string Email
        {
            get
            {
                CanReadProperty("Email", true);
                return _email;
            }
            set
            {
                CanWriteProperty("Email", true);
                if (value == null) value = string.Empty;
                if (!_email.Equals(value))
                {
                    _email = value;
                    PropertyHasChanged("Email");
                }
            }
        }

        

        protected override object GetIdValue()
        {
            return _id.ToString().Trim().Replace("\"", "\\\"");
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Contato
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Contato
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ContatoViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Contato
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ContatoAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Contato
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ContatoEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Contato
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ContatoDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Contato()
        { /* require use of factory method */ }

        public static Contato NewContato()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Contato");
            return DataPortal.Create<Contato>();
        }

        public static Contato GetContato(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Contato");
            return DataPortal.Fetch<Contato>(new Criteria(id));
        }

        public override Contato Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Contato");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Contato");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Contato");

            return base.Save();
        }

        public static void DeleteContato(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Contato");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;

            }
        }


        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteFetch(cn, criteria);
            }//using

        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();



                    //load child object(s)
                    FetchChildren(dr);
                }
            }//using
        }

        private string GetFetchScript(Criteria criteria)
        {
            return "SELECT "
                 + "Id, "
                 + "Telefone, "
                 + "Celular, "
                 + "Fax, "
                 + "CaixaPostal, "
                 + "Email "
                 + "FROM contatotb "
                 + "WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;
            _id = new Guid(dr["Id"].ToString().Trim().Replace("\"", "\\\""));
            _telefone = dr.GetString("Telefone");
            _celular = dr.GetString("Celular");
            _fax = dr.GetString("Fax");
            _caixaPostal = dr.GetString("CaixaPostal");
            _email = dr.GetString("Email");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteInsert(cn);

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - Contatotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();
                cm.ExecuteNonQuery();
            }//using
        }

        private string GetInsertScript()
        {
            return "INSERT INTO contatotb "
                +"( Id, Telefone, Celular, Fax, CaixaPostal, Email) "
                + " VALUES (\""
                + _id.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _telefone.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _celular.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _fax.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _caixaPostal.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _email.ToString().Trim().Replace("\"", "\\\"") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - Contatotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private string GetUpdateScript()
        {
            return "Update contatotb set "
                    + "Telefone=\"" + _telefone.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Celular=\"" + _celular.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Fax=\"" + _fax.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "CaixaPostal=\"" + _caixaPostal.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Email=\"" + _email.ToString().Trim().Replace("\"", "\\\"") + "\" "
                    + "WHERE Id=\"" + _id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - Contatotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from contatotb WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}